import web
import sys
import os
import numpy as np
import fastdtw
from scikits.audiolab import wavread
import scikits.talkbox
from scikits.talkbox import features
from scikits.talkbox.features import mfcc

urls = (
    '/demo', 'hello',
    '/calcmfcc', 'calcmfcc',
    '/calcdist', 'calcdist',
    '/addtemplate', 'addtemplate',
)

db = web.database(dbn='mysql', user='root', pw='root', db='audiotemplate')


def str2list(sstr, spliter):
    arr=sstr.split(spliter)
    b=[]
    for s in arr:
        if(s!=''):
            b.append(int(s))
    return b
        
def mydist(a, b):
    i_dist=0
    for i in range(0, len(a)):
        i_dist=i_dist+abs(a[i]-b[i])
    return i_dist/len(a)
    
def mfcc2str(llist):
    re=''
    for i in llist:
        temp=''
        for j in i:
            temp=temp+str(j)+'@'
        re=re+temp+'#'
    return re
    
def str2mfcc(sstr):
    temp=sstr.split('#')
    temp.pop()
    re=[]
    for lstr in temp:
        llist=[]
        arr=lstr.split('@')
        arr.pop()
        for elem in arr:
            llist.append(float(elem))
        re.append(llist)
    return re 
    
def data2mfcc(sstr):
    data=str2list(sstr, ',')
    temp=mfcc(data)[0]
    return mfcc2str(temp)
    
def dist(str1, str2):
    mf1=str2mfcc(str1)
    np1=np.array(mf1)
    mf2=str2mfcc(str2)
    np2=np.array(mf2)
    re=fastdtw.fastdtw(np1, np2, 1, mydist)[0]
    return re
        

class hello:
    def GET(self, name):
        return name

class calcmfcc:
    def POST(self):
        data=web.data()               
        return data2mfcc(data)
        
class calcdist:
    def POST(self):
        form=web.input(name="a", data="")
        name=form.name
        mf=data2mfcc(form.data)
        temps=db.query('select * from template where name="' + name + '"')
        mindist=999999
        for temp in temps:            
            mindist=min(mindist, dist(mf, temp.mfcc_text))
        return mindist
        
class addtemplate:
    def POST(self):
        form=web.input(name="a", data="")
        mf=data2mfcc(form.data)
        db.insert('template', name=form.name, mfcc_text=mf)
        return "ok"
        

if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()